<script setup lang="ts" name="RolePermissions">
import { ref, reactive, watch, onMounted, defineProps, defineEmits } from 'vue'
import { ElMessage, ElTree } from 'element-plus'
import type { Role, Permission } from '@/model/user-role-model'
import { getPermissionTree, updateRolePermissions, getRoleDetail } from '@/request/user-role-api'

const props = defineProps<{
  visible: boolean
  role: Role | null
}>()

const emit = defineEmits<{
  (e: 'update:visible', visible: boolean): void
  (e: 'updated'): void
}>()

// 权限树引用
const permissionTreeRef = ref<InstanceType<typeof ElTree>>()

// 加载状态
const loading = ref(false)

// 权限树数据
const treeData = ref<Permission[]>([])

// 选中的权限ID列表
const checkedPermissions = ref<number[]>([])

// 获取权限树
const fetchPermissionTree = async () => {
  loading.value = true
  try {
    const res = await getPermissionTree()
    if (res.code === 0 && res.data) {
      treeData.value = res.data
    } else {
      ElMessage.error(res.errorMsg || '获取权限数据失败')
    }
  } catch (error) {
    console.error('获取权限树出错：', error)
    ElMessage.error('获取权限数据失败')
  } finally {
    loading.value = false
  }
}

// 提交权限设置
const submitPermissions = async () => {
  if (!props.role) {
    ElMessage.error('未选择角色')
    return
  }
  
  try {
    // 获取当前选中的权限ID列表
    const permission_ids = checkedPermissions.value
    
    const res = await updateRolePermissions(props.role.id, { permission_ids })
    
    if (res.code === 0) {
      ElMessage.success('权限设置成功')
      closeDialog()
      emit('updated')
    } else {
      ElMessage.error(res.errorMsg || '权限设置失败')
    }
  } catch (error) {
    console.error('设置权限出错：', error)
    ElMessage.error('权限设置失败')
  }
}

// 树节点配置
const defaultProps = {
  children: 'children',
  label: 'name',
}

// 关闭弹窗
const closeDialog = () => {
  emit('update:visible', false)
}

// 初始化选中的权限
const initCheckedPermissions = () => {
  if (props.role && (props.role.permission_ids || props.role.permissions)) {
    checkedPermissions.value = (props.role.permission_ids || props.role.permissions) as number[]
  } else {
    checkedPermissions.value = []
  }
}

// 获取角色详情（用于加载已分配权限）
const fetchRoleDetail = async () => {
  if (!props.role) return
  try {
    const res = await getRoleDetail(props.role.id)
    if (res.code === 0 && res.data) {
      checkedPermissions.value = res.data.permission_ids || []
      // 同步到树选择
      permissionTreeRef.value?.setCheckedKeys(checkedPermissions.value)
    } else {
      ElMessage.error(res.errorMsg || '获取角色详情失败')
    }
  } catch (error) {
    console.error('获取角色详情出错：', error)
    ElMessage.error('获取角色详情失败')
  }
}

// 处理权限选择变化
const handleCheckChange = () => {
  // 通过获取当前选中的keys更新选中的权限ID列表
  const keys = permissionTreeRef.value?.getCheckedKeys() as number[] || []
  checkedPermissions.value = keys
}

// 监听角色数据变化
watch(
  () => props.role,
  () => {
    if (props.visible) {
      initCheckedPermissions()
    }
  },
  { immediate: true }
)

// 监听弹窗显示状态
watch(
  () => props.visible,
  (newVal) => {
    if (newVal) {
      fetchPermissionTree()
      initCheckedPermissions()
      fetchRoleDetail()
    }
  },
  { immediate: true }
)

// 获取选中的权限ID列表
const getCheckedKeys = () => {
  return permissionTreeRef.value?.getCheckedKeys() || []
}

// 全选
const checkAll = () => {
  // 获取所有可选节点的keys
  const allKeys = getAllNodeKeys(treeData.value)
  permissionTreeRef.value?.setCheckedKeys(allKeys)
}

// 获取所有节点的ID
const getAllNodeKeys = (nodes: Permission[]): number[] => {
  const keys: number[] = []
  const traverse = (nodes: Permission[]) => {
    if (!nodes) return
    nodes.forEach(node => {
      keys.push(node.id)
      if (node.children && node.children.length > 0) {
        traverse(node.children)
      }
    })
  }
  traverse(nodes)
  return keys
}

// 取消全选
const uncheckAll = () => {
  permissionTreeRef.value?.setCheckedKeys([])
}
</script>

<template>
  <el-dialog
    title="权限分配"
    :model-value="visible"
    @update:model-value="(val) => emit('update:visible', val)"
    :close-on-click-modal="false"
    width="600px"
    @closed="closeDialog"
  >
    <div v-if="role" class="mb-4">
      <div class="text-lg font-medium mb-2">{{ role.name }}</div>
      <div class="text-gray-500">{{ role.description }}</div>
    </div>
    
    <div class="border p-4 rounded bg-gray-50">
      <div class="flex justify-between mb-4">
        <div class="text-md font-medium">权限列表</div>
        <div>
          <el-button type="primary" link @click="checkAll">全选</el-button>
          <el-button type="info" link @click="uncheckAll">取消全选</el-button>
        </div>
      </div>
      
      <el-tree
        ref="permissionTreeRef"
        v-loading="loading"
        :data="treeData"
        :props="defaultProps"
        node-key="id"
        show-checkbox
        default-expand-all
        :default-checked-keys="checkedPermissions"
        @check="handleCheckChange"
      />
    </div>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="submitPermissions">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>
